package com.irdstudio.apicenter.gateway.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;


public class YcHttpClientUtil {
	static final Logger lg = Logger.getLogger(YcHttpClientUtil.class);
	public YcHttpClientUtil() {
	}

	/**
	 * 进行httpGet请求
	 * 
	 * @param url
	 *            请求的url参数直接已？拼接
	 * @return
	 * @throws IOException 
	 * @throws Exception 
	 */
	public static JSONObject httpGet(String url) throws Exception{
		CloseableHttpClient httpClient = null;
		// 创建默认的httpClient实例
		try {
			httpClient = HttpClients.createDefault();
			// 用get方法发送HTTP请求
			HttpGet get = new HttpGet(url);
			CloseableHttpResponse httpResponse = null;
			// 发送get请求
			httpResponse = httpClient.execute(get);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			// 通讯成功，状态:200
			if (statusCode == HttpStatus.OK.value()) {
				HttpEntity entity = httpResponse.getEntity();

				if (null == entity) {
					throw new Exception("通讯异常:httpResponse.getEntity得到的对象为null");
				}
				// 返回JSON对象
				return JSONObject.parseObject(EntityUtils.toString(entity));
			} else {
				throw new Exception("与微信接口通讯异常:  statusCode=" + statusCode);
			}
		} catch (Exception e) {
			lg.error(e.getMessage(), e);
		}finally{
			try {
				if (httpClient != null) {
					httpClient.close();
					httpClient = null;
				}
			} catch (Exception e2) {}
		}
		return null;
	}

	/**
	 * POST方式发起http请求
	 */
	public static JSONObject httpPost(String url, Map<String, String> paramMap) throws Exception{
		CloseableHttpClient httpClient = null;
		try {
			// 创建默认的httpClient实例
			httpClient = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);
			// 设置内容格式
			post.setHeader("Content-Type",
					"application/x-www-form-urlencoded; charset=UTF-8");
			post.setHeader("Connection", "keep-alive");
			// 创建参数列表
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			for (Entry<String, String> mapEntry : paramMap.entrySet()) {
				list.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry
						.getValue()));
			}
			// URL格式编码
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list,
					"UTF-8");
			post.setEntity(uefEntity);
			// 执行请求
			CloseableHttpResponse httpResponse = httpClient.execute(post);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.OK.value()) {
				HttpEntity entity = httpResponse.getEntity();
				if (null != entity) {
					return JSONObject.parseObject(EntityUtils.toString(entity));
				}else{
					throw new Exception("通讯异常:httpResponse.getEntity得到的对象为null");
				}
			}else{
				throw new Exception("与微信接口通讯异常:  statusCode=" + statusCode);
			}
		} catch (Exception e) {
			lg.info("调用httpPost()方法异常");
			throw new RuntimeException(e.getMessage(),e);
		}finally{
			try {
				if (httpClient != null) {
					httpClient.close();
					httpClient = null;
				}
			} catch (Exception e2) {}
		}
		
	}

	public static void main(String[] args) {
		//X5MqlApiR3sldGe2_xj_N2D9KScDGrZeIzqlLhs4QT9X-EKhZ3FEfrWp34HndkVi
		//String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx829e7312041af188&corpsecret=F4ia77C6_Ge8ivSSJorZZhhf8afEj61Llw3YDiiAKKiGzmf7cGy6TVrYJ7vIiHyN";
		String url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=lqMwn554Wkp8TasTv9BRbNqPFNrPfzjizCbkohHPGHdeNY7FgHOkUU2i-wq0vhI1&code=7f33c78ee6fc2ef56e63fd12156db660";
		//
		//75b8477e901ded31891cc9e13757e8c8
		//Map<String, String> paramMap = new HashMap<String, String>();// 请求参数
		//paramMap.put("corpid", "wx829e7312041af188");
		//paramMap.put("corpsecret","F4ia77C6_Ge8ivSSJorZZhhf8afEj61Llw3YDiiAKKiGzmf7cGy6TVrYJ7vIiHyN");
		// HttpClientUtil httpClientutil = new HttpClientUtil(url, paramMap);
		JSONObject jSONObject = null;
		try {
			jSONObject = YcHttpClientUtil.httpGet(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(jSONObject.toString());

	}
}